package cn.yuanqiao.archive.liyong.service.impl;

import cn.yuanqiao.archive.appManager.domain.TenantCategory;
import cn.yuanqiao.archive.appManager.mapper.TenantCategoryMapper;
import cn.yuanqiao.archive.liyong.domain.AppointmentForm;
import cn.yuanqiao.archive.liyong.mapper.AppointmentFormMapper;
import cn.yuanqiao.archive.liyong.service.IAppointmentFormService;
import cn.yuanqiao.common.constant.Constants;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ProjectName: cn.yuanqiao.archive.liyong.service.impl
 * @ClassName: AppointmentFormServiceImpl
 * @Author: lenovo
 * @Description: hbWang
 * @Date: 2024/10/29 17:21
 * @Version: 1.0
 **/
@Service
public class AppointmentFormServiceImpl implements IAppointmentFormService {
    @Autowired
    private AppointmentFormMapper appointmentFormMapper;
    @Autowired
    private TenantCategoryMapper tenantCategoryMapper;

    /**
     * 查询【预约单】
     *
     * @param id 【预约单】主键
     * @return 【预约单】
     */
    @Override
    public AppointmentForm selectAppointmentFormByID(String id) {
        return appointmentFormMapper.selectAppointmentFormByID(id, new AppointmentForm().getTableName());
    }


    /**
     * 查询【预约单】列表
     *
     * @param appointmentForm 【预约单】
     * @return 【预约单】
     */
    @Override
    public List<AppointmentForm> selectAppointmentFormList(AppointmentForm appointmentForm) {
        if (!SecurityUtils.isDagly()) appointmentForm.setUserId(SecurityUtils.getUserId());
        return appointmentFormMapper.selectAppointmentFormListUser(appointmentForm);
    }


    /**
     * 根据用户名查询未提交的借阅单
     *
     * @return 【预约单】
     */
    @Override
    public List<AppointmentForm> selectNotAppointmentForm() {
        AppointmentForm appointmentForm = new AppointmentForm();
        appointmentForm.setStatus("3");
        appointmentForm.setCreateId(SecurityUtils.getUserId());
        return appointmentFormMapper.selectAppointmentFormList(appointmentForm);
    }

    /**
     * 添加预约单
     *
     * @param appointmentForm
     * @return
     */
    @Override
    public int addAppointmentForm(AppointmentForm appointmentForm) {
        int i = appointmentFormMapper.selectAppointmentFormByDaId(appointmentForm.getDaId(), appointmentForm.getTableName(), null);
        if (i > 0) {
            throw new ServiceException("本条档案已经被预约,请等归还后再预约!");
        }
        List<AppointmentForm> appointmentForms = appointmentFormMapper.selectAppointmentFormBycreateId(SecurityUtils.getUserId(), appointmentForm.getTableName());
        if (appointmentForms.size() > 0) {
            throw new ServiceException("预约单里已经有一条档案了,请先提交后再添加档案!");
        }

        String searchtable = appointmentForm.getSubTableName();
        String tablenametype = searchtable.substring(searchtable.length() - 3, searchtable.length() - 2);
        String tenantCode = SecurityUtils.getLoginUser().getSysUser().getTenantCode();
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryBytableName(tablenametype.equalsIgnoreCase("F") ?
                        "FILE_TABLE_NAME" : tablenametype.equalsIgnoreCase("V") ? "FOLDER_TABLE_NAME" : "ITEM_TABLE_NAME",
                tenantCode + Constants.BIG_TABLE_NAME, appointmentForm.getSubTableName());
        List<Map<String, Object>> maps = appointmentFormMapper.selectList("*", " select * from " + searchtable + " where id = " + appointmentForm.getDaId());
        if (maps != null && maps.size() > 0) {
            Map<String, Object> map = maps.get(0);
            appointmentForm.setBgqx(map.containsKey("BGQX") ? map.get("BGQX").toString() : "");
            appointmentForm.setRq(map.containsKey("RQ") ? map.get("RQ").toString() : "");
            appointmentForm.setDh(map.containsKey("DH") ? map.get("DH").toString() : "");
            appointmentForm.setTitle(map.containsKey("TITLE") ? map.get("TITLE").toString() : map.containsKey("XMMC") ? map.get("XMMC").toString() : "");
        }
        appointmentForm.setDaType(tablenametype);
        appointmentForm.setCategoryId(tenantCategory.getCategoryId());
        appointmentForm.setStatus("3");
        appointmentForm.setId(SnowflakeIdGenerator.generateId());
        appointmentForm.setCreateId(SecurityUtils.getUserId());
        appointmentForm.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        return appointmentFormMapper.insertAppointmentForm(appointmentForm);
    }

    /**
     * 提交【预约单】
     *
     * @param appointmentForm 【预约单】
     * @return 结果
     */
    @Override
    @Transactional
    public int insertAppointmentForm(AppointmentForm appointmentForm) {
        int i = appointmentFormMapper.selectAppointmentFormByDaId(appointmentForm.getDaId(), appointmentForm.getTableName(), null);
        if (i > 0) {
            throw new ServiceException("本条档案已经被预约,请等归还后再预约!");
        }
        List<AppointmentForm> appointmentForms = appointmentFormMapper.selectAppointmentFormBycreateId(SecurityUtils.getUserId(), appointmentForm.getTableName());
        if (appointmentForms != null && appointmentForms.size() > 0) {
            for (AppointmentForm af : appointmentForms) {
                appointmentForm.setStatus("0");
                appointmentForm.setId(af.getId());
                appointmentForm.setDaType(af.getDaType());
                appointmentForm.setSubTableName(af.getSubTableName());
            }
        } else {
            throw new ServiceException("请勿提交空的预约单!");
        }
        appointmentForm.setCreateTime(DateUtils.getNowDate());
        String daIds = updateData(appointmentForm.getDaId(), appointmentForm.getDaType(), appointmentForm.getSubTableName(), 1);
        appointmentForm.setDaIds(daIds);
        appointmentFormMapper.updateAppointmentForm(appointmentForm);
        return 1;
    }

    /**
     * 修改【预约单】修改次日12点前未借阅的档案
     *
     * @param tenantCode 租户编码
     * @return 结果
     */
    @Override
    @Transactional
    public void jobState(String tenantCode) {
        List<AppointmentForm> appointmentForms = appointmentFormMapper.selectAppointmentFormByDaIdList(null, "0", tenantCode + "_APPOINTMENT_FORM",
                null, "1");
        List<String> id = new ArrayList<>();
        if (appointmentForms != null && appointmentForms.size() > 0) {
            for (AppointmentForm af : appointmentForms) {
                LocalDateTime borrowTime = LocalDateTime.ofInstant(af.getBorrowTime().toInstant(), ZoneId.systemDefault());
                LocalDateTime nextDayNoon = borrowTime.toLocalDate().plusDays(1).atTime(12, 0);
                LocalDateTime now = LocalDateTime.now();
                //当前时间大于  归还时间次日12点
                if (now.isAfter(nextDayNoon)) {
                    id.add(String.valueOf(af.getId()));
                    updateData(String.valueOf(af.getId()),af.getDaType(),af.getSubTableName(),0);
                }
            }
        }
        if (id != null && id.size() > 0) {
            appointmentFormMapper.updateTableData("update " + tenantCode
                    + "_APPOINTMENT_FORM set STATUS =1 where  id in ('" + id.stream().collect(Collectors.joining("','")) + "')");
        }

    }


    /**
     * 修改【预约单】
     *
     * @param appointmentForm 【预约单】
     * @return 结果
     */
    @Override
    public int updateAppointmentForm(AppointmentForm appointmentForm) {
        return appointmentFormMapper.updateAppointmentForm(appointmentForm);
    }

    /**
     * 批量删除【预约单】
     *
     * @param ids 需要删除的【预约单】主键
     * @return 结果
     */
    @Override
    public int deleteAppointmentFormByIDs(String ids) {
        String[] split = ids.split(",");
        return appointmentFormMapper.deleteAppointmentFormByIDs(split, new AppointmentForm().getTableName());
    }

    /**
     * 删除【预约单】信息
     *
     * @param id 【预约单】主键
     * @return 结果
     */
    @Override
    public int deleteAppointmentFormByID(String id) {
        return appointmentFormMapper.deleteAppointmentFormByID(id, new AppointmentForm().getTableName());
    }

    /**
     * 修改档案信息
     *
     * @param ids  主键id
     * @param type 类型  0 件 1 卷 3 项目
     * @return
     */
    @Transactional
    @Override
    public String updateData(String ids, String type, String subTableName, Integer statue) {
        //获取当前登录用户信息
        String tenantCode = SecurityUtils.getLoginUser().getSysUser().getTenantCode();
        //查询门类信息
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryBytableName(type.equalsIgnoreCase("F") ? "FILE_TABLE_NAME" : type.equalsIgnoreCase("V") ? "FOLDER_TABLE_NAME" : "ITEM_TABLE_NAME",
                tenantCode + Constants.BIG_TABLE_NAME, subTableName);
        StringBuilder selectSql = new StringBuilder();
        List<String> daIds = new ArrayList<>();
        List<String> folderIds = new ArrayList<>();
        List<String> itemIds = new ArrayList<>();

        selectSql.append(" select yf.FOLDER_ID,yf.DA_ID,tf.ITEM_ID from " + tenantCode + Constants.BIG_TABLE_FOLDER_NAME + " yf ");
        selectSql.append(" left JOIN " + tenantCode + Constants.BIG_TABLE_NAME_ITEM + "  tf on yf.FOLDER_ID =  tf.FOLDER_ID ");
        //组件信息
        if ("F".equalsIgnoreCase(type)) {
            selectSql.append(" where yf.DA_ID in  (" + ids + ") ");
            List<Map<String, Object>> maps = appointmentFormMapper.selectList(" COALESCE(FOLDER_ID,0) AS FOLDER_ID, COALESCE(DA_ID,0) AS DA_ID,  COALESCE(ITEM_ID,0) AS ITEM_ID ", selectSql.toString());
            if (maps != null && maps.size() > 0) {
                daIds.addAll(maps.stream().map(m -> m.get("DA_ID").toString()).collect(Collectors.toList()));
                folderIds.addAll(maps.stream().map(m -> m.get("FOLDER_ID").toString()).collect(Collectors.toList()));
                itemIds.addAll(maps.stream().map(m -> m.get("ITEM_ID").toString()).collect(Collectors.toList()));
            }
            daIds.add(ids);
        } else if ("V".equalsIgnoreCase(type)) {
            //组卷
            selectSql.append(" where yf.FOLDER_ID in (" + ids + ")");
            List<Map<String, Object>> maps = appointmentFormMapper.selectList(" COALESCE(FOLDER_ID,0) AS FOLDER_ID, COALESCE(DA_ID,0) AS DA_ID,  COALESCE(ITEM_ID,0) AS ITEM_ID ", selectSql.toString());
            if (maps != null && maps.size() > 0) {
                daIds.addAll(maps.stream().map(m -> m.get("DA_ID").toString()).collect(Collectors.toList()));
                folderIds.addAll(maps.stream().map(m -> m.get("FOLDER_ID").toString()).collect(Collectors.toList()));
                itemIds.addAll(maps.stream().map(m -> m.get("ITEM_ID").toString()).collect(Collectors.toList()));
            }
            folderIds.add(ids);
        } else if ("X".equalsIgnoreCase(type)) {
            //项目
            selectSql.append(" where tf.ITEM_ID in (" + ids + ")");
            List<Map<String, Object>> maps = appointmentFormMapper.selectList(" COALESCE(FOLDER_ID,0) AS FOLDER_ID, COALESCE(DA_ID,0) AS DA_ID,  COALESCE(ITEM_ID,0) AS ITEM_ID ", selectSql.toString());
            if (maps != null && maps.size() > 0) {
                daIds.addAll(maps.stream().map(m -> m.get("DA_ID").toString()).collect(Collectors.toList()));
                folderIds.addAll(maps.stream().map(m -> m.get("FOLDER_ID").toString()).collect(Collectors.toList()));
                itemIds.addAll(maps.stream().map(m -> m.get("ITEM_ID").toString()).collect(Collectors.toList()));
            }
            itemIds.add(ids);
        }
        if (daIds != null && daIds.size() > 0 && StringUtils.isNotEmpty(tenantCategory.getFileTableName())) {
            StringBuilder sqlSubtable = new StringBuilder();
            sqlSubtable.append(" update " + tenantCategory.getFileTableName() + " set is_appointment = " + statue);
            sqlSubtable.append(" where ID IN ('" + daIds.stream().distinct().collect(Collectors.joining("','")) + "');");
            sqlSubtable.append(" update " + tenantCode + Constants.BIG_TABLE_YQDA + " set is_appointment =" + statue);
            sqlSubtable.append(" where DA_ID IN ('" + daIds.stream().distinct().collect(Collectors.joining("','")) + "');");
            appointmentFormMapper.updateTableData(sqlSubtable.toString());
        }
        if (folderIds != null && folderIds.size() > 0 && StringUtils.isNotEmpty(tenantCategory.getFolderTableName())) {
            StringBuilder sqlSubtable = new StringBuilder();
            sqlSubtable.append(" update " + tenantCategory.getFolderTableName() + " set is_appointment = " + statue);
            sqlSubtable.append(" where ID IN ('" + folderIds.stream().distinct().collect(Collectors.joining("','")) + "');");
            sqlSubtable.append(" update " + tenantCode + Constants.BIG_TABLE_YQFOLDER + " set is_appointment = " + statue);
            sqlSubtable.append(" where FOLDER_ID IN ('" + folderIds.stream().distinct().collect(Collectors.joining("','")) + "');");
            appointmentFormMapper.updateTableData(sqlSubtable.toString());
        }
        if (itemIds != null && itemIds.size() > 0 && StringUtils.isNotEmpty(tenantCategory.getItemTableName())) {
            StringBuilder sqlSubtable = new StringBuilder();
            sqlSubtable.append(" update " + tenantCategory.getItemTableName() + " set is_appointment = " + statue);
            sqlSubtable.append(" where ID IN ('" + itemIds.stream().distinct().collect(Collectors.joining("','")) + "');");
            sqlSubtable.append(" update " + tenantCode + Constants.BIG_TABLE_YQITEM + " set is_appointment = " + statue);
            sqlSubtable.append(" where ITEM_ID IN ('" + itemIds.stream().distinct().collect(Collectors.joining("','")) + "');");
            appointmentFormMapper.updateTableData(sqlSubtable.toString());
        }
        List<String> sumIds = new ArrayList();
        sumIds.addAll(itemIds);
        sumIds.addAll(daIds);
        sumIds.addAll(folderIds);
        return sumIds.stream().distinct().collect(Collectors.joining(","));
    }
}
